package inbound.http;

import filter.HttpRequestFilter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;
import model.HttpConfig;
import outbound.http.HobHandler;

import java.util.ArrayList;
import java.util.List;

/**
 * @author dsp
 * @date 2021-04-04
 */
public class HibHandler extends ChannelInboundHandlerAdapter {

    private HttpConfig httpConfig;
    private HobHandler handler;
    private List<HttpRequestFilter> filters = new ArrayList<>();

    public HibHandler(HttpConfig httpConfig) {
        this.httpConfig = httpConfig;
        this.handler = new HobHandler(httpConfig);
        this.filters = httpConfig.getRequestFilters();
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        try {
            FullHttpRequest fullRequest = (FullHttpRequest) msg;
            String uri = fullRequest.uri();
            System.out.println("请求url为: " + uri);
            String value = fullRequest.content().toString(CharsetUtil.UTF_8);
            System.out.println("请求content为: " + value);
            handler.handle(fullRequest, ctx, filters);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }

}
